package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * RTRIM(str)
 *
 * Returns the string str with trailing space characters removed.
 *
 * mysql> SELECT RTRIM('barbar   ');
 *         -> 'barbar'
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午6:03:35
 * @since 5.1.0
 */
public class Rtrim extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"RTRIM"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        if (Utils.isNull(args[0])) {
            return null;
        }

        String str = Type.StringType.convert(args[0]);

        int len = str.length();

        while ((0 < len) && (str.charAt(len - 1) <= ' ')) {
            len--;
        }

        if (len < str.length())
            return str.substring(0, len);
        else
            return str;
    }
}
